﻿Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.Net
Imports System.IO

Partial Public Class DownloadTamplate : Inherits System.Web.UI.Page
    Dim sharePointListPath As String = ConfigurationManager.AppSettings("SharePointServer")
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        'Dim docinfo As New System.IO.DirectoryInfo(Server.MapPath("~/Template/"))
        'If Not docinfo.Exists Then
        '    docinfo.Create()
        'End If
        'Dim ActivitypeCode As String = TryCast(Request("atCode"), String)
        'Dim PlanYear As String = TryCast(Request("PlanYear"), String)
        'If Not IsNothing(ActivitypeCode) And ActivitypeCode <> "" And Not IsNothing(PlanYear) And PlanYear <> "" Then
        '    Dim actDT As New ActTypeDS.ActivityTypesDataTable
        '    Dim actAdap As New ActTypeDSTableAdapters.ActivityTypesTableAdapter
        '    actDT = actAdap.GetDataByCode(ActivitypeCode, PlanYear)
        '    If actDT.Rows.Count > 0 Then
        '        If actDT.Rows(0)("TemplateName").ToString() <> "" Then
        '            Dim ext As String = FindContantType(System.IO.Path.GetExtension(actDT.Rows(0)("TemplateName").ToString()))
        '            If ext <> "" Then
        '                Response.ContentType = ext
        '                Response.AppendHeader("Content-Disposition", "attachment; filename=" + actDT.Rows(0)("TemplateName").ToString())
        '                Response.TransmitFile(sharePointListPath + actDT.Rows(0)("TemplateName").ToString())
        '                Response.End()
        '            End If
        '        End If
        '    End If
        'End If

        Dim file_name As String
        Try
            Dim ActivitypeCode As String = TryCast(Request("atCode"), String)
            Dim PlanYear As String = TryCast(Request("PlanYear"), String)
            Dim CmmtCode As String = TryCast(Request("cmmt_Code"), String)
            If Not IsNothing(CmmtCode) And CmmtCode <> "" And Not IsNothing(PlanYear) And PlanYear <> "" Then
                Dim actDT As New MasterDataSet.CmmtsDataTable
                Dim actAdap As New MasterDataSetTableAdapters.CmmtsTableAdapter
                actDT = actAdap.GetDataBy2(PlanYear, CmmtCode)
                If actDT.Rows.Count > 0 Then
                    If actDT.Rows(0)("TemplateName").ToString() <> "" Then
                        Dim ext As String = FindContantType(System.IO.Path.GetExtension(actDT.Rows(0)("TemplateName").ToString()))
                        If ext <> "" Then
                            file_name = actDT.Rows(0)("TemplateName").ToString()
                            Try ' Add By Orn 28/06/2558
                                Dim webRequest As HttpWebRequest = webRequest.Create(sharePointListPath & file_name)
                                webRequest.Credentials = CredentialCache.DefaultCredentials
                                webRequest.Method = "GET"
                                webRequest.ContentType = "application/x-www-form-urlencoded"
                                webRequest.CookieContainer = New CookieContainer()

                                Dim bytesProcessed As Integer = 0
                                Dim remoteStream As Stream
                                Dim localStream As Stream
                                Dim resp As WebResponse = Nothing
                                Dim memStream As New MemoryStream(1023)

                                resp = webRequest.GetResponse()
                                If Not resp Is Nothing Then
                                    remoteStream = resp.GetResponseStream()
                                    Dim myBuffer As Byte()
                                    ReDim myBuffer(1023)


                                    Dim bytesRead As Integer
                                    bytesRead = remoteStream.Read(myBuffer, 0, 1023)

                                    Do While (bytesRead > 0)
                                        'localStream.Write(myBuffer, 0, bytesRead)
                                        memStream.Write(myBuffer, 0, bytesRead)
                                        bytesProcessed += bytesRead
                                        bytesRead = remoteStream.Read(myBuffer, 0, 1023)

                                    Loop
                                    'localStream.Close()
                                    Dim bytest As Byte() = memStream.ToArray()
                                    memStream.Close()

                                    Response.Clear()
                                    Response.ClearHeaders()
                                    Response.ClearContent()
                                    'Response.AddHeader("Content-Disposition", "attachment; filename=" + file_name)
                                    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file_name, System.Text.Encoding.UTF8))
                                    Response.AddHeader("Content-Length", bytesProcessed.ToString())
                                    Response.ContentType = "text/plain"
                                    If Response.Headers("GENERATOR") = "Microsoft Sharepoint" Then
                                        Response.Write("หากไม่สามารถดาวน์โหลดได้กรุณา <a href='" & sharePointListPath & file_name & "'>คลิกที่นี่</a>")
                                        Exit Sub
                                    End If
                                    Response.Flush()
                                    Response.BinaryWrite(bytest)
                                    Response.End()
                                End If
                            Catch ex As Exception
                                Response.Write("ไม่พบไฟล์ " + file_name)
                            End Try
                        End If
                    End If
                End If
            ElseIf Not IsNothing(ActivitypeCode) And ActivitypeCode <> "" And Not IsNothing(PlanYear) And PlanYear <> "" Then
                Dim actDT As New ActTypeDS.ActivityTypesDataTable
                Dim actAdap As New ActTypeDSTableAdapters.ActivityTypesTableAdapter
                actDT = actAdap.GetDataByCode(ActivitypeCode, PlanYear)
                If actDT.Rows.Count > 0 Then
                    If actDT.Rows(0)("TemplateName").ToString() <> "" Then
                        Dim ext As String = FindContantType(System.IO.Path.GetExtension(actDT.Rows(0)("TemplateName").ToString()))
                        If ext <> "" Then
                            file_name = actDT.Rows(0)("TemplateName").ToString()
                            Try ' Add By Orn 28/06/2558
                                Dim webRequest As HttpWebRequest = webRequest.Create(sharePointListPath & file_name)
                                webRequest.Credentials = CredentialCache.DefaultCredentials
                                webRequest.Method = "GET"
                                webRequest.ContentType = "application/x-www-form-urlencoded"
                                webRequest.CookieContainer = New CookieContainer()

                                Dim bytesProcessed As Integer = 0
                                Dim remoteStream As Stream
                                Dim localStream As Stream
                                Dim resp As WebResponse = Nothing
                                Dim memStream As New MemoryStream(1023)

                                resp = webRequest.GetResponse()
                                If Not resp Is Nothing Then
                                    remoteStream = resp.GetResponseStream()
                                    Dim myBuffer As Byte()
                                    ReDim myBuffer(1023)


                                    Dim bytesRead As Integer
                                    bytesRead = remoteStream.Read(myBuffer, 0, 1023)

                                    Do While (bytesRead > 0)
                                        'localStream.Write(myBuffer, 0, bytesRead)
                                        memStream.Write(myBuffer, 0, bytesRead)
                                        bytesProcessed += bytesRead
                                        bytesRead = remoteStream.Read(myBuffer, 0, 1023)

                                    Loop
                                    'localStream.Close()
                                    Dim bytest As Byte() = memStream.ToArray()
                                    memStream.Close()

                                    Response.Clear()
                                    Response.ClearHeaders()
                                    Response.ClearContent()
                                    'Response.AddHeader("Content-Disposition", "attachment; filename=" + file_name)
                                    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file_name, System.Text.Encoding.UTF8))
                                    Response.AddHeader("Content-Length", bytesProcessed.ToString())
                                    Response.ContentType = "text/plain"
                                    If Response.Headers("GENERATOR") = "Microsoft Sharepoint" Then
                                        Response.Write("หากไม่สามารถดาวน์โหลดได้กรุณา <a href='" & sharePointListPath & file_name & "'>คลิกที่นี่</a>")
                                        Exit Sub
                                    End If
                                    Response.Flush()
                                    Response.BinaryWrite(bytest)
                                    Response.End()
                                End If
                            Catch ex As Exception
                                Response.Write("ไม่พบไฟล์ " + file_name)
                            End Try
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            Response.Write("หากไม่สามารถดาวน์โหลดได้กรุณา <a href='" & sharePointListPath & file_name & "'>คลิกที่นี่</a>")
        End Try
    End Sub
    Private Function FindContantType(extension As String) As String
        Dim contentType As String = ""
        Select Case extension
            Case ".xla", ".xlc", ".xlm", "xlt", ".xlw", ".xls", ".xlsx"
                contentType = "application/vnd.ms-excel"
            Case ".txt"
                contentType = "text/plain"
            Case ".doc", ".docx", ".dot"
                contentType = "application/msword"
            Case ".pdf"
                contentType = "application/pdf"
        End Select
        Return contentType
    End Function

End Class

